package com.imti.mall.product.service.impl;
import com.imti.mall.model.cms.pojo.CmsPrefrenceAreaProductRelation;
import com.imti.mall.model.cms.pojo.CmsSubjectProductRelation;
import com.imti.mall.model.pms.pojo.*;
import com.imti.mall.model.pms.vo.PmsProductParam;
import com.imti.mall.model.pms.vo.PmsProductVo;
import com.imti.mall.product.dao.PmsProductCategoryDao;
import com.imti.mall.product.dao.ProductDao;
import com.imti.mall.product.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class ProductServiceImpl   implements ProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Autowired
    ProductDao productDao;
    @Autowired
    PmsMemberPriceService pmsMemberPriceService;
    @Autowired
    PmsProductLadderService pmsProductLadderService;
    @Autowired
    PmsProductFullReductionService pmsProductFullReductionService;
    @Autowired
    PmsSkuStockService pmsSkuStockService;
    @Autowired
    PmsProductAttributeValueService pmsProductAttributeValueService;
    @Autowired
    CmsSubjectProductRelationService cmsSubjectProductRelationService;
    @Autowired
    CmsPrefrenceAreaProductRelationService cmsPrefrenceAreaProductRelationService;

    /**
     * 根据条件查询商品信息
     * @param
     * @return
     */
    @Override
    public List<PmsProduct> findPmsProduct(Map<String, Object> map) {
        return productDao.findPmsProduct(map);

    }
    /**
     * 总条数查询商品信息
     * @param pmsProduct
     * @return
     */
    @Override
    public Integer countPmsProduct(PmsProduct pmsProduct) {

        return productDao.countPmsProduct(pmsProduct);
    }


    /**
     * 根据id查询商品信息
     * @param
     * @return
     */
    @Override
    public PmsProduct getPmsProductById(Integer id) {

        return productDao.getPmsProductById(id);
    }


    /**
     * 根据id删除商品信息
     * @param
     * @return
     */
    @Override
    public Integer delPmsProductById(PmsProduct pmsProduct) {
        return productDao.delPmsProduct(pmsProduct);
    }
    /**
     * 修改商品信息
     * @param productParam
     * @return
     */
    @Override
    public Integer updategetPmsProductById(PmsProductParam productParam) {
        int count;
        //创建商品
        PmsProduct product = productParam;
        productDao.updategetPmsProductById(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = product.getId();
        //会员价格
        //商品会员价格{memberLevelId: 0,memberPrice: 0,memberLevelName: null}list
        List<PmsMemberPrice> memberPriceList=pmsMemberPriceService.getPmsMemberPriceId(productId.intValue());
        relateAndUpdateList(pmsMemberPriceService, productParam.getMemberPriceList(), productId,memberPriceList);
        //阶梯价格
        //商品阶梯价格
        // productLadderList: [{count: 0,discount: 0,price: 0}],
        List<PmsProductLadder> productLadderList =pmsProductLadderService.getPmsProductLadderProductId(productId.intValue());
        relateAndUpdateList(pmsProductLadderService, productParam.getProductLadderList(), productId,productLadderList);
        //满减价格
        //商品满减
        //    productFullReductionList: [{fullPrice: 0, reducePrice: 0}],
        List<PmsProductFullReduction> productFullReductionList=pmsProductFullReductionService.getPmsProductFullReductionId(productId.intValue());
        relateAndUpdateList(pmsProductFullReductionService, productParam.getProductFullReductionList(), productId,productFullReductionList);
        //处理sku的编码
        //商品sku库存信息{lowStock: 0, pic: '', price: 0, sale: 0, skuCode: '', spData: '', stock: 0}
        //skuStockList: [],
        List<PmsSkuStock> skuStockList=pmsSkuStockService.getPmsSkuStockproductProductId(productId.intValue());

        handleSkuStockCode(productParam.getSkuStockList(),productId);
        //添加sku库存信息
        relateAndUpdateList(pmsSkuStockService, productParam.getSkuStockList(), productId,skuStockList);
        PmsProductAttributeValue pmsProductAttributeValue=new PmsProductAttributeValue();
        //商品属性值表返回商品属性相关{productAttributeId: 0, value: ''}
        pmsProductAttributeValue.setProductId(productId);
        List<PmsProductAttributeValue> pmsProductAttributeValueList= pmsProductAttributeValueService.findPmsProductAttributeValue(pmsProductAttributeValue);
        //添加商品参数,添加自定义商品规格
        relateAndUpdateList(pmsProductAttributeValueService, productParam.getProductAttributeValueList(), productId,pmsProductAttributeValueList);
        //关联专题
        //    商品相关专题{subjectId: 0}
        //    subjectProductRelationList: []
        List<CmsSubjectProductRelation> subjectProductRelationList  = cmsSubjectProductRelationService.getCmsSubjectProductRelationProductId(productId.intValue());
        relateAndUpdateList(cmsSubjectProductRelationService, productParam.getSubjectProductRelationList(), productId,skuStockList);
        //关联优选
        // 商品相关优选{prefrenceAreaId: 0}
        //    prefrenceAreaProductRelationList: [], //商品相关优选{prefrenceAreaId: 0}
        List<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelationList  = cmsPrefrenceAreaProductRelationService.getCmsPrefrenceAreaProductRelationProductId(productId.intValue());
        relateAndUpdateList(cmsPrefrenceAreaProductRelationService, productParam.getPrefrenceAreaProductRelationList(), productId,prefrenceAreaProductRelationList);
        count = 1;
        return count;
    }

    /**
     * 上架下架修改
     * @param pmsProduct
     * @return
     */
    @Override
    public Integer updatePmsProductPublishStatusById(PmsProductVo pmsProduct) {
        return productDao.updatePmsProductPublishStatusByid(pmsProduct);
    }

    /**
     * 新品不是新品修改
     * @param pmsProduct
     * @return
     */
    @Override
    public Integer updatePmsProductNewStatusById(PmsProductVo pmsProduct) {
        return productDao.updatePmsProductNewStatusById(pmsProduct);
    }

    /**
     * 推荐 不推荐修改
     * @param pmsProduct
     * @return
     */
    @Override
    public Integer updatePmsProductRecommandStatusById(PmsProductVo pmsProduct) {
        return productDao.updatePmsProductRecommandStatusById(pmsProduct);
    }

    /**
     * 添加商品信息
     * @param productParam
     * @return
     */
    @Override
    public Integer addPmsProduct(PmsProductParam productParam) {
        int count;
        //创建商品
        PmsProduct product = productParam;
        product.setId(null);
        productDao.insert(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = product.getId();
        //会员价格
        relateAndInsertList(pmsMemberPriceService, productParam.getMemberPriceList(), productId);
        //阶梯价格
        relateAndInsertList(pmsProductLadderService, productParam.getProductLadderList(), productId);
        //满减价格
        relateAndInsertList(pmsProductFullReductionService, productParam.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(),productId);
        //添加sku库存信息
        relateAndInsertList(pmsSkuStockService, productParam.getSkuStockList(), productId);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(pmsProductAttributeValueService, productParam.getProductAttributeValueList(), productId);
        //关联专题
        relateAndInsertList(cmsSubjectProductRelationService, productParam.getSubjectProductRelationList(), productId);
        //关联优选
        relateAndInsertList(cmsPrefrenceAreaProductRelationService, productParam.getPrefrenceAreaProductRelationList(), productId);
        count = 1;
        return count;
    }

    /**
     * sku编码生成
     * @param skuStockList
     * @param productId
     */
    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if(CollectionUtils.isEmpty(skuStockList)){return;}
        for(int i=0;i<skuStockList.size();i++){
            PmsSkuStock skuStock = skuStockList.get(i);
            if(StringUtils.isEmpty(skuStock.getSkuCode())){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i+1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    /**
     * 建立和插入关系表操作
     *
     * @param service       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object service, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)){ return;}
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = service.getClass().getMethod("addList", List.class);
            insertList.invoke(service, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 建立和插入关系表操作
     *
     * @param service       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndUpdateList(Object service, List dataList, Long productId ,List delList) {
        try {
            if (CollectionUtils.isEmpty(dataList)){return;} 
            for (Object item : dataList) {
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method deleteList = service.getClass().getMethod("deleteList", List.class);
            deleteList.invoke(service, delList);
            Method insertList = service.getClass().getMethod("updateList", List.class);
            insertList.invoke(service, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
